package com.hxz.graduationdesign.util;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Year;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAccessor;
import java.util.Date;

public class FormattingTool {

    //数字格式化
    public static int parseNumber(String text) {
        if (text == null || text.isEmpty()) {
            return 0;
        }

        try {
            // 1. 预处理字符串
            text = text.trim()
                    .replaceAll(",", "")  // 移除千位分隔符
                    .replaceAll("\\s+", "") // 移除所有空白字符
                    .replace(" ", "");     // 额外确保移除空格

            // 2. 处理中文单位
            if (text.contains("万") || text.contains("亿")) {
                // 提取数字部分
                String numberPart = text.replaceAll("[^0-9.]", "");
                if (numberPart.isEmpty()) {
                    return 0;
                }

                double number = Double.parseDouble(numberPart);

                if (text.contains("亿")) {
                    return (int) Math.round(number * 100000000);
                } else if (text.contains("万")) {
                    return (int) Math.round(number * 10000);
                }
            }

            // 3. 处理普通数字
            return (int) Math.round(Double.parseDouble(text));

        } catch (NumberFormatException e) {
            System.err.println("数字格式转换错误 - 原始文本: \"" + text + "\"");
            return 0;
        }
    }

    // 字符串时长转秒数整形
    public static Integer convertToSeconds(String timeStr){
        String[] parts = timeStr.split(":");

        if (parts.length < 2 || parts.length > 3) {
            throw new IllegalArgumentException("无效时间格式，示例: 00:00 或 00:00:00");
        }

        try {
            int hours = 0;
            int minutes;
            int seconds;

            if (parts.length == 3) { // HH:MM:SS
                hours = Integer.parseInt(parts[0]);
                minutes = Integer.parseInt(parts[1]);
                seconds = Integer.parseInt(parts[2]);
            } else { // MM:SS
                minutes = Integer.parseInt(parts[0]);
                seconds = Integer.parseInt(parts[1]);
            }

            return hours * 3600 + minutes * 60 + seconds;

        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("包含非数字字符");
        }
    }

    // 秒数整形转字符串时长
    public static String formatDuration(int duration) {
        int hours = duration / 3600;
        int minutes = (duration % 3600) / 60;
        int seconds = duration % 60;

        if (hours > 0) {
            return String.format("%02d:%02d:%02d", hours, minutes, seconds);
        } else {
            return String.format("%02d:%02d", minutes, seconds);
        }
    }


    //字符串日期转Date
    private static final DateTimeFormatter[] FORMATTERS = {
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"), // 带时间
            DateTimeFormatter.ofPattern("yyyy-MM-dd"),          // 完整日期
            DateTimeFormatter.ofPattern("M-d"),                 // 1-1, 12-1
            DateTimeFormatter.ofPattern("MM-dd")                // 01-01, 12-01
    };

    public static Date parseDate(String dateStr) throws DateTimeParseException {
        dateStr = dateStr.trim(); // 去除前后空格

        // 1. 尝试解析带时间的日期（yyyy-MM-dd HH:mm:ss）
        try {
            LocalDateTime dateTime = LocalDateTime.parse(dateStr, FORMATTERS[0]);
            return Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
        } catch (DateTimeParseException ignored) {}

        // 2. 尝试解析完整日期（yyyy-MM-dd）
        try {
            LocalDate localDate = LocalDate.parse(dateStr, FORMATTERS[1]);
            return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        } catch (DateTimeParseException ignored) {}

        // 3. 尝试解析短格式（M-d 或 MM-dd），并补全年份
        for (int i = 2; i < FORMATTERS.length; i++) {
            try {
                TemporalAccessor parsed = FORMATTERS[i].parse(dateStr);
                int month = parsed.get(ChronoField.MONTH_OF_YEAR);
                int day = parsed.get(ChronoField.DAY_OF_MONTH);

                LocalDate currentYearDate = LocalDate.of(Year.now().getValue(), month, day);
                return Date.from(currentYearDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
            } catch (DateTimeParseException ignored) {}
        }

        // 4. 尝试解析 "xx分钟前" 或 "xx小时前"
        if (dateStr.endsWith("分钟前")) {
            int minutesAgo = Integer.parseInt(dateStr.replace("分钟前", ""));
            LocalDateTime pastTime = LocalDateTime.now().minusMinutes(minutesAgo);
            return Date.from(pastTime.atZone(ZoneId.systemDefault()).toInstant());
        } else if (dateStr.endsWith("小时前")) {
            int hoursAgo = Integer.parseInt(dateStr.replace("小时前", ""));
            LocalDateTime pastTime = LocalDateTime.now().minusHours(hoursAgo);
            return Date.from(pastTime.atZone(ZoneId.systemDefault()).toInstant());
        }

        // 5. 尝试解析 "昨天"
        if ("昨天".equals(dateStr)) {
            LocalDate yesterday = LocalDate.now().minusDays(1);
            return Date.from(yesterday.atStartOfDay(ZoneId.systemDefault()).toInstant());
        }

        // 如果都不匹配，抛出异常
        throw new DateTimeParseException(
                "支持的日期格式：\n" +
                        "- yyyy-MM-dd HH:mm:ss\n" +
                        "- yyyy-MM-dd\n" +
                        "- M-d（如 12-1）\n" +
                        "- MM-dd（如 12-01）\n" +
                        "- XX分钟前 / XX小时前",
                dateStr, 0
        );
    }

    //提取视频网址中的bv号
    static String getBv(String url){
        try {
            URI uri = new URI(url);
            String path = uri.getPath(); // 获取路径部分 "/video/BV1Wv4y1Z7Cw/"
            return path.split("/")[2];
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    //    SentimentAnalyzer sentimentAnalyzer = getSentimentAnalyzer();
    public static SentimentAnalyzer getSentimentAnalyzer(){
        return SentimentAnalyzer.getInstance();
    }

    //    ChineseSegmenter chineseSegmenter = getChineseSegmenter();
    public static ChineseSegmenter  getChineseSegmenter() throws IOException {

        return new ChineseSegmenter();
    }

}
